from basehandler.BaseHandler import BaseHandler
import codecs
import uuid
from datahandler.DataHandler import DataHandler
from keys import *

class UsernameEmailGetter(BaseHandler):       
    def ifloggedin(self):
        if self.auth.get_user_by_session()==None:
            return False
        else:
            return True
    
    def redirectIfNotLogin(self):
        if self.auth.get_user_by_session()==None:
            self.redirect('login')
        else:
            return True
        
    
    def getheader(self):
        if self.ifloggedin():
            return 'header/header_logged.html'
        else:
            return 'header/header.html'

    
    def getheaderUser(self):
        if self.ifloggedin():
            context={headerKey:'header/header_logged.html',usernameKey:self.getUserName()}
        else:
            context={headerKey:'header/header.html',usernameKey:'Guest'}
        return context
    
    def getEmailAddress(self):
        user_session=self.auth.get_user_by_session()
        user=self.auth.store.user_model.get_by_auth_token(user_session['user_id'], user_session['token'])
        email=user[0].auth_ids[0]
        return email
    
    def getUserName(self):
        user_session=self.auth.get_user_by_session()
        user=self.auth.store.user_model.get_by_auth_token(user_session['user_id'], user_session['token'])
        email=user[0].auth_ids[0]
        datahandler=DataHandler()
        userInfo=datahandler.getUserInfo({emailKey:email})
        try:
            name=userInfo['name']
            return name
        except:
            return None
        
    def getFirstName(self):
        try:
            return self.session['firstname']
        except:
            return None
    def getLastName(self):
        try: 
            return self.session['lastname']
        except:
            return None
    def defaultRequestAuthenticationHandle(self,guestAction):
        result={}
        if self.ifloggedin():
            result[ifloggedinKey]=True
        elif guestAction:
            result[ifloggedinKey]='guest'
        else:
            result[ifloggedinKey]=False
        return result
        
class UniqueIdGenerator(BaseHandler):
    def getUniqueId(self):
        return str(uuid.uuid1())
    
    def get(self):
        return self.response.write(self.getUniqueId().strip())

class CommonUtils:
    def getUniqueId(self):
        return str(uuid.uuid1())
        
    def getlegalname(self,name):
        return name.replace("'","").replace(" ","_").replace(".","_").replace("-","_").replace("(","_").replace(")","_")
    
    def checkNullInMap(self,map,replacement):
        keys=map.keys()
        for key in keys:
            map[key]=self.checkNull(map[key], replacement)
        return map
    
    #list contains maps
    def checkNullInList(self,list,replacement):
        resultList=[]
        for item in list:
            item=self.checkNullInMap(item, replacement)
            resultList.append(item)
        return resultList
    
    def checkNull(self,data,replacement):
        if data==None:
            return replacement
        else:
            try:
                return data
            except:
                return str(data)
    

class BirdInfoGetter:
    def __init__(self,country):
        filename='statichandler/'+CommonUtils().getlegalname(country)
        try:
            lines=codecs.open(filename,'r','utf-8').readlines()
            self.birdslist=lines
        except:
            pass
        
    def getScientificNameEndemicStatus(self,birdName,country):
        try:
            for line in self.birdslist:
                if line.find(birdName)!=-1:
                    tokens=line.strip().split(',')
                    return {'scientificName':self.validate(tokens[3]),'conservationStatus':self.validate(tokens[4]),'endemicStatus':self.validate(tokens[5])}
        except:
            return None
    
    def validate(self,name):
        name=name.replace("\"","")
        if len(name)==0:
            name="-"
        return name

class LanguageGetter(BaseHandler):
    def getLanguage(self):
        return lang_english
        
        
